package com.edu.neusoft.elec_shop.service;

import com.edu.neusoft.elec_shop.domain.ShoppingCart;
import com.edu.neusoft.elec_shop.mapper.ShoppingCartMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    //添加商品到购物车
    public int addToShoppingCart(ShoppingCart shoppingCart) {
        // 先查询购物车中是否已存在该商品
        ShoppingCart existingCart = shoppingCartMapper.selectByUserIdAndGoodsId(shoppingCart.getUserId(), shoppingCart.getGoodsId());

        if (existingCart!= null) {
            // 如果已存在，更新数量和金额
            int newQuantity = Integer.parseInt(existingCart.getQuantity()) + Integer.parseInt(shoppingCart.getQuantity());
            double newCartAmount = Double.parseDouble(existingCart.getCartAmount()) + Double.parseDouble(shoppingCart.getCartAmount());

            existingCart.setQuantity(String.valueOf(newQuantity));
            existingCart.setCartAmount(String.valueOf(newCartAmount));

            return shoppingCartMapper.updateByPrimaryKeySelective(existingCart);
        } else {
            // 如果不存在，直接插入新记录
            return shoppingCartMapper.insert(shoppingCart);
        }
    }

    //将商品移出购物车
    public int deleteByGoodsId(Long cartId) {return shoppingCartMapper.deleteByGoodsId(cartId);}

    // 根据用户ID获取购物车列表
    public List<ShoppingCart> getShoppingCartByUserId(Long userId) {return shoppingCartMapper.getShoppingCartByUserId(userId);}

}